package cn.edu.zime.tjh.handler;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.DatagramPacket;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.util.function.Consumer;

public class AsyncUDPClientHandler extends SimpleChannelInboundHandler<DatagramPacket> {
    private Consumer<String> messageCallback;
    private Consumer<String> statusCallback;
    
    public AsyncUDPClientHandler(Consumer<String> messageCallback, Consumer<String> statusCallback) {
        this.messageCallback = messageCallback;
        this.statusCallback = statusCallback;
    }
    
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, DatagramPacket packet) {
        // 接收回显
        ByteBuf content = packet.content();
        String response = content.toString(CharsetUtil.UTF_8);
        
        InetSocketAddress sender = packet.sender();
        String formattedMessage = String.format("[%s:%d] %s",
                sender.getAddress().getHostAddress(),
                sender.getPort(),
                response);
        
        if (messageCallback != null) {
            messageCallback.accept(formattedMessage);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        if (statusCallback != null) {
            statusCallback.accept("UDP客户端错误: " + cause.getMessage());
        }
        cause.printStackTrace();
    }
}